import { Tabs } from 'antd';
import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import styled from 'styled-components';
import { BaseTable, utils, NumberView } from '@/components/BaseTable';
import {
  DIVISOR_MONEY,
  FIXED_MONEY,
  RenderNumberPct,
  RenderNumber,
} from '@/utils/buildReturnValue';
import dayjs from 'dayjs';

const TableCell = styled.div`
  display: flex;
  align-items: center;
  text-align: center;
  justify-content: center;
  flex-direction: column;
`;

function setZCReturn(key1, key2) {
  return [
    {
      name: '增量回款',
      key: key1,
      rowspan: 1,
      colspan: 1,
    },
    {
      name: '存量回款',
      key: key2,
      rowspan: 1,
      colspan: 1,
    },
  ];
}

function ProjectOverallYearTarget({ treeData }) {
  const keyList = [
    'yearReturnTotal',
    'yearActualReturnTotal',
    'yearCalculateReturnTotal',
    'signNotReturn',
    'yearSign',
    'yearEarlyReceivable',
    'yearEndReceivable',
    'vsPreviousEditionDifference',
  ];
  const titleTree = [
    {
      name: '年度回款',
      key: 'yearReturnMoney',
      colspan: 3,
      rowspan: 1,
      children: [
        {
          name: '年度回款合计',
          key: 'yearReturnTotal',
          rowspan: 1,
          colspan: 1,
        },
        {
          key: 'yearActualReturnTotal',
          name: '年度实际回款',
          rowspan: 1,
          colspan: 1,
        },
        {
          key: 'yearCalculateReturnTotal',
          name: '年度预测回款',
          rowspan: 1,
          colspan: 1,
        },
      ],
    },
    {
      name: '已签未回',
      key: 'signNotReturn',
      rowspan: 2,
      colspan: 1,
    },
    {
      name: '年度签约',
      key: 'yearSign',
      rowspan: 2,
      colspan: 1,
    },
    {
      name: '年初应收账款',
      key: 'yearEarlyReceivable',
      rowspan: 2,
      colspan: 1,
    },
    {
      name: '年末应收账款',
      key: 'yearEndReceivable',
      rowspan: 2,
      colspan: 1,
    },
    {
      name: 'VS上一版差异',
      key: 'vsPreviousEditionDifference',
      rowspan: 2,
      colspan: 1,
    },
  ];
  const fixedColumns = [];
  _.forEach(keyList, item => {
    fixedColumns.push({
      key: item,
      dataKey: item,
      width: 155,
      align: 'right',
      dataGetter: ({ rowData }) => rowData[item] / 10000,
      cellRenderer: data => {
        if (item === 'vsPreviousEditionDifference') {
          return (
            <RenderNumberPct value={data.rowData[item] / DIVISOR_MONEY} precision={FIXED_MONEY} />
          );
        }
        return (
          <div style={{ textAlign: 'right', width: '100%' }}>
            <NumberView {...data} precision={4} />
          </div>
        );
      },
    });
  });
  return (
    <BaseTable
      fixHeight={_.isEmpty(treeData) ? 248 : 96}
      headerHeight={[30, 30]}
      fixedColumns={fixedColumns}
      headerRenderer={utils.getHeaderRenderer(titleTree, 2)}
      treeData={treeData}
    />
  );
}

function YearTargetDetailVo({ year, treeData }) {
  const keyList = [
    'yearEarlyReceivable', // 年初应收账款
    'yearSign', // 年度签约
    'annualActualIncrementalReturn', // 年度实际数-增量回款
    'annualActualStoreReturn', // 年度实际数-存量回款
    'annualCalculateIncrementalReturn', // 年度测算数-增量回款
    'annualCalculateStoreReturn', // 年度测算数-存量回款
    'annualAdjustIncrementalReturn', // 年度调整数-增量回款
    'annualAdjustStoreReturn', // 年度调整数-存量回款
    'yearSignNotReturn', // 年度已签未回
    'annualTotalIncrementalReturn', // 年度回款合计-增量回款
    'annualTotalStoreReturn', // 年度回款合计-存量回款
    'annualTotalReturnTotal', // 年度回款合计-回款合计
    'annualTotalYearEndReceivable', // 年度回款合计-年末应收账款
  ];
  const titleTree = [
    {
      name: '年初应收账款',
      key: 'yearEarlyReceivable',
      colspan: 1,
      rowspan: 2,
    },
    {
      name: '年度签约',
      key: 'yearSign',
      colspan: 1,
      rowspan: 2,
    },
    {
      name: '年度实际数',
      key: 'annualActual',
      colspan: 2,
      rowspan: 1,
      children: [...setZCReturn('annualActualIncrementalReturn', 'annualActualStoreReturn')],
    },
    {
      name: '年度测算数',
      key: 'annualCalculate',
      colspan: 2,
      rowspan: 1,
      children: [...setZCReturn('annualCalculateIncrementalReturn', 'annualCalculateStoreReturn')],
    },
    {
      name: '年度调整数',
      key: 'annualAdjust',
      colspan: 2,
      rowspan: 1,
      children: [...setZCReturn('annualAdjustIncrementalReturn', 'annualAdjustStoreReturn')],
    },
    {
      name: (
        <TableCell>
          <div>年度已签未回</div>
          <div>回款数</div>
        </TableCell>
      ),
      key: 'yearSignNotReturn',
      colspan: 1,
      rowspan: 2,
    },
    {
      name: `${year}年度回款合计`,
      key: 'annualTotal',
      colspan: 2,
      rowspan: 1,
      children: [
        ...setZCReturn('annualTotalIncrementalReturn', 'annualTotalStoreReturn'),
        {
          name: '回款合计',
          key: 'annualTotalReturnTotal',
          rowspan: 1,
          colspan: 1,
        },
        {
          name: '年末应收账款',
          key: 'annualTotalYearEndReceivable',
          rowspan: 1,
          colspan: 1,
        },
      ],
    },
  ];
  const fixedColumns = [];
  _.forEach(keyList, item => {
    fixedColumns.push({
      key: item,
      dataKey: item,
      title: '金额（万元）',
      width: 110,
      align: 'right',
      dataGetter: ({ rowData }) => rowData[item] / 10000,
      cellRenderer: data => (
        <div style={{ textAlign: 'right', width: '100%' }}>
          <NumberView {...data} precision={4} />
        </div>
      ),
    });
  });
  return (
    <BaseTable
      fixHeight={_.isEmpty(treeData) ? 248 : 131}
      headerHeight={[30, 30, 30]}
      fixedColumns={fixedColumns}
      headerRenderer={utils.getHeaderRenderer(titleTree, 2)}
      treeData={treeData}
    />
  );
}

function MonthTargetDetailVoList({ year, treeData }) {
  // 实际月
  const actualMonth = [
    'monthEarlyReceivable', // 月初应收账款
    'monthSign', // 月度签约
    'monthlyTotalIncrementalReturn', // 月度回款合计-增量回款
    'monthlyTotalStoreReturn', // 月度回款合计-存量回款
    'monthlyTotalReturnTotal', // 月度回款合计-回款合计
    'signReturnRate', // 累计签约回款率
    'annualOverallReturnRate', // 年度综合回款率
  ];
  // 当前月
  const currentMonth = [
    'monthEarlyReceivable', // 月初应收账款
    'monthSign', // 月度签约
    'monthlyActualIncrementalReturn', // 月度实际数-增量回款
    'monthlyActualStoreReturn', // 月度实际数-存量回款
    'monthlyCalculateIncrementalReturn', // 月度测算数-增量回款
    'monthlyCalculateStoreReturn', // 月度测算数-存量回款
    'monthlyAdjustIncrementalReturn', // 月度调整数-增量回款
    'monthlyAdjustStoreReturn', // 月度调整数-存量回款
    'monthSignNotReturn', // 月度已签未回回款数
    'refundable', // 期初应退回款数
    'monthlyTotalIncrementalReturn', // 月度回款合计-增量回款
    'monthlyTotalStoreReturn', // 月度回款合计-存量回款
    'monthlyTotalReturnTotal', // 月度回款合计-回款合计
    'monthlyTotalMonthEndReceivable', // 月度回款合计-月末应收账款
    'signReturnRate', // 累计签约回款率
    'annualOverallReturnRate', // 年度综合回款率
  ];
  // 计划月
  const planMonth = [
    'monthEarlyReceivable', // 月初应收账款
    'monthSign', // 月度签约
    'monthlyCalculateIncrementalReturn', // 月度测算数-增量回款
    'monthlyCalculateStoreReturn', // 月度测算数-存量回款
    'monthlyAdjustIncrementalReturn', // 月度调整数-增量回款
    'monthlyAdjustStoreReturn', // 月度调整数-存量回款
    'monthSignNotReturn', // 月度已签未回回款数
    'monthlyTotalIncrementalReturn', // 月度回款合计-增量回款
    'monthlyTotalStoreReturn', // 月度回款合计-存量回款
    'monthlyTotalReturnTotal', // 月度回款合计-回款合计
    'monthlyTotalMonthEndReceivable', // 月度回款合计-月末应收账款
    'signReturnRate', // 累计签约回款率
    'annualOverallReturnRate', // 年度综合回款率
  ];
  const [fixedColumnsS, setFixedColumns] = useState([]);
  const [titleTreeS, setTitleTree] = useState([]);
  useEffect(() => {
    if (year) {
      const titleTree = [];
      const fixedColumns = [];
      for (let i = 1; i <= 12; i += 1) {
        // 是否是当前时间之前
        const isCurrentTimeBefore = dayjs(`${year}-${i}`).isBefore();
        // 是否是当前时间
        const isCurrentTime = dayjs(`${year}-${i}`).isSame(dayjs().format('YYYY-MM'));
        // 实际月
        if (!isCurrentTime && isCurrentTimeBefore) {
          titleTree.push({
            name: `${year}-${i < 10 ? '0' : ''}${i}`,
            key: `${year}${i}`,
            children: [
              {
                name: '期初应收账款',
                key: `${i}-field_6`,
                colspan: 1,
                rowspan: 2,
              },
              {
                name: '本期签约',
                key: `${i}-monthSign`,
                colspan: 1,
                rowspan: 2,
              },
              {
                name: '本期回款合计（实际数）',
                key: `${i}-monthlyTotal`,
                colspan: 3,
                rowspan: 1,
                children: [
                  {
                    name: '增量回款',
                    key: `${i}-monthlyTotalIncrementalReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '存量回款',
                    key: `${i}-monthlyTotalStoreReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '回款合计',
                    key: `${i}-monthlyTotalReturnTotal`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
              {
                name: '回款率',
                key: `${i}-ReturnRate`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '累计签约回款率',
                    key: `${i}-signReturnRate`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '年度综合回款率',
                    key: `${i}-annualOverallReturnRate`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
            ],
          });
          _.forEach(actualMonth, v => {
            // 是百分比
            const isPercentage = v === 'signReturnRate' || v === 'annualOverallReturnRate';
            fixedColumns.push({
              key: `${year}}-${i}-${v}`,
              dataKey: `${year}}-${i}-${v}`,
              title: isPercentage ? '（%）' : '金额（万元）',
              align: 'right',
              width: 100,
              dataGetter: ({ rowData }) => {
                let val = rowData[i - 1][v] / 10000;
                let suffix = '';
                let precision = 4;
                if (isPercentage) {
                  val = rowData[i - 1][v] * 100;
                  suffix = '%';
                  precision = 3;
                }
                return <RenderNumber value={val} precision={precision} suffix={suffix} />;
              },
            });
          });
        }
        // 当前月
        if (isCurrentTime) {
          titleTree.push({
            name: `${year}-${i < 10 ? '0' : ''}${i}`,
            key: `${year}${i}`,
            children: [
              {
                name: '期初应收账款',
                key: `${i}-field_6`,
                colspan: 1,
                rowspan: 2,
              },
              {
                name: '本期签约',
                key: `${i}-monthSign`,
                colspan: 1,
                rowspan: 2,
              },
              {
                name: '本期实际数',
                key: `${i}-monthlyActual`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '增量回款',
                    key: `${i}-monthlyActualIncrementalReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '存量回款',
                    key: `${i}-monthlyActualStoreReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
              {
                name: '本期测算数',
                key: `${i}-monthlyCalculate`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '增量回款',
                    key: `${i}-monthlyCalculateIncrementalReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '存量回款',
                    key: `${i}-monthlyCalculateStoreReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
              {
                name: '本期调整数',
                key: `${i}-monthlyAdjust`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '增量回款',
                    key: `${i}-monthlyAdjustIncrementalReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '存量回款',
                    key: `${i}-monthlyAdjustStoreReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
              {
                name: (
                  <TableCell>
                    <div>本期已签未回</div>
                    <div>回款数</div>
                  </TableCell>
                ),
                key: `${i}-monthSignNotReturn`,
                colspan: 1,
                rowspan: 2,
              },
              {
                name: (
                  <TableCell>
                    <div>本期期初应退</div>
                    <div>回款数</div>
                  </TableCell>
                ),
                key: `${i}-refundable`,
                colspan: 1,
                rowspan: 2,
              },
              {
                name: '本期回款合计',
                key: `${i}-monthlyTotal`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '增量回款',
                    key: `${i}-monthlyTotalIncrementalReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '存量回款',
                    key: `${i}-monthlyTotalStoreReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '回款合计',
                    key: `${i}-monthlyTotalReturnTotal`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '期末应收账款',
                    key: `${i}-monthlyTotalMonthEndReceivable`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
              {
                name: '回款率',
                key: `${i}-ReturnRate`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '累计签约回款率',
                    key: `${year}${i}-signReturnRate`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '年度综合回款率',
                    key: `${year}${i}-annualOverallReturnRate`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
            ],
          });
          _.forEach(currentMonth, v => {
            // 是百分比
            const isPercentage = v === 'signReturnRate' || v === 'annualOverallReturnRate';
            fixedColumns.push({
              key: `${year}-${i}-${v}`,
              dataKey: `${year}-${i}-${v}`,
              title: isPercentage ? '（%）' : '金额（万元）',
              align: 'right',
              width: 100,
              dataGetter: ({ rowData }) => {
                let val = rowData[i - 1][v] / 10000;
                let suffix = '';
                let precision = 4;
                if (isPercentage) {
                  val = rowData[i - 1][v] * 100;
                  suffix = '%';
                  precision = 3;
                }
                return <RenderNumber value={val} precision={precision} suffix={suffix} />;
              },
            });
          });
        }
        // 计划月
        if (!isCurrentTime && !isCurrentTimeBefore) {
          titleTree.push({
            name: `${year}-${i < 10 ? '0' : ''}${i}`,
            key: `${year}${i}`,
            children: [
              {
                name: '期初应收账款',
                key: `${i}-field_6`,
                colspan: 1,
                rowspan: 2,
              },
              {
                name: '本期签约',
                key: `${i}-monthSign`,
                colspan: 1,
                rowspan: 2,
              },
              {
                name: '本期测算数',
                key: `${i}-monthlyCalculate`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '增量回款',
                    key: `${i}-monthlyCalculateIncrementalReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '存量回款',
                    key: `${i}-monthlyCalculateStoreReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
              {
                name: '本期调整数',
                key: `${i}-monthlyAdjust`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '增量回款',
                    key: `${i}-monthlyAdjustIncrementalReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '存量回款',
                    key: `${i}-monthlyAdjustStoreReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
              {
                name: (
                  <TableCell>
                    <div>本期已签未回</div>
                    <div>回款数</div>
                  </TableCell>
                ),
                key: `${i}-monthSignNotReturn`,
                colspan: 1,
                rowspan: 2,
              },
              {
                name: '本期回款合计',
                key: `${i}-monthlyTotal`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '增量回款',
                    key: `${i}-monthlyTotalIncrementalReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '存量回款',
                    key: `${i}-monthlyTotalStoreReturn`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '回款合计',
                    key: `${i}-monthlyTotalReturnTotal`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '期末应收账款',
                    key: `${i}-monthlyTotalMonthEndReceivable`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
              {
                name: '回款率',
                key: `${i}-ReturnRate`,
                colspan: 2,
                rowspan: 1,
                children: [
                  {
                    name: '累计签约回款率',
                    key: `${i}-signReturnRate`,
                    colspan: 1,
                    rowspan: 1,
                  },
                  {
                    name: '年度综合回款率',
                    key: `${i}-annualOverallReturnRate`,
                    colspan: 1,
                    rowspan: 1,
                  },
                ],
              },
            ],
          });
          _.forEach(planMonth, v => {
            // 是百分比
            const isPercentage = v === 'signReturnRate' || v === 'annualOverallReturnRate';
            fixedColumns.push({
              key: `${year}-${i}-${v}`,
              dataKey: `${year}-${i}-${v}`,
              title: isPercentage ? '（%）' : '金额（万元）',
              align: 'right',
              width: 100,
              dataGetter: ({ rowData }) => {
                let val = rowData[i - 1][v] / 10000;
                let suffix = '';
                let precision = 4;
                if (isPercentage) {
                  val = rowData[i - 1][v] * 100;
                  suffix = '%';
                  precision = 3;
                }
                return <RenderNumber value={val} precision={precision} suffix={suffix} />;
              },
            });
          });
        }
      }
      setFixedColumns(fixedColumns);
      setTitleTree(titleTree);
    }
  }, [year]);

  return (
    <BaseTable
      fixHeight={_.isEmpty(treeData) ? 278 : 161}
      expandColumnKey="name"
      headerHeight={[30, 30, 30, 30]}
      fixedColumns={fixedColumnsS}
      headerRenderer={utils.getHeaderRenderer(titleTreeS, 3)}
      treeData={treeData}
    />
  );
}

export default function SubComponentsTow({ data }) {
  const [tabKey, setTabKey] = useState('');
  const [dataSource1, setDataSource1] = useState([]);
  const [dataSource2, setDataSource2] = useState([]);
  const [dataSource3, setDataSource3] = useState([]);
  useEffect(() => {
    if (!_.isEmpty(data)) {
      setTabKey(data[0].year);
    }
  }, [data]);
  useEffect(() => {
    if (tabKey) {
      const currentData = _.last(_.filter(data, x => x.year === tabKey));
      setDataSource1([
        {
          id: 0,
          ...currentData.projectOverallYearTarget,
        },
      ]);
      setDataSource2([
        {
          id: 0,
          ...currentData.yearTargetDetailVo,
        },
      ]);
      setDataSource3([
        {
          id: 0,
          ...currentData.monthTargetDetailVoList,
        },
      ]);
    }
  }, [tabKey]);

  if (_.isEmpty(data)) return <></>;
  // console.log(columns, 'columns', dataSource)
  return (
    <div className="approve-box-content-paragraph">
      <Tabs onChange={key => setTabKey(_.toNumber(key))}>
        {_.map(data, item => (
          <Tabs.TabPane tab={item.year} key={item.year} />
        ))}
      </Tabs>
      <ProjectOverallYearTarget treeData={dataSource1} />
      <div
        className="approve-box-content-paragraph-sub-title"
        style={{ marginTop: 5 }}
      >{`${tabKey}年年度回款指标详情`}</div>
      <YearTargetDetailVo year={tabKey} treeData={dataSource2} />
      <div
        className="approve-box-content-paragraph-sub-title"
        style={{ marginTop: 5 }}
      >{`${tabKey}年月度回款指标详情`}</div>
      <MonthTargetDetailVoList year={tabKey} treeData={dataSource3} />
    </div>
  );
}
